package com.android.flickr;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.aetrion.flickr.Flickr;
import com.aetrion.flickr.FlickrException;
import com.aetrion.flickr.REST;
import com.aetrion.flickr.RequestContext;
import com.aetrion.flickr.auth.Auth;
import com.aetrion.flickr.auth.AuthInterface;
import com.aetrion.flickr.auth.Permission;
import com.aetrion.flickr.uploader.UploadMetaData;
import com.aetrion.flickr.uploader.Uploader;

public class flickrTalkr {
	String photo, title, description, secret,auth_token;
	String api_key;
	String frobapi_sig;
	String tokapi_sig;
	String api_sig;
	String frob = null;
	public flickrTalkr()
	{
		api_key = FlickrPickr.API_KEY;
		secret = FlickrPickr.API_SECRET;
	}
	
	public String getFrob()
	{
		String s = secret+"api_key"+api_key;
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		}
		md.update(s.getBytes(),0,s.length());
//		md.h
		byte[] byteSig = md.digest();
		
		StringBuffer hexString = new StringBuffer();
		for (int i=0;i<byteSig.length;i++) {
			String hex = Integer.toHexString(0xFF & byteSig[i]);
			if (hex.length() == 1) {
			    // could use a for loop, but we're only dealing with a single byte
			    hexString.append('0');
			}
			hexString.append(hex);
		}
		api_sig = hexString.toString();
		URL url = null;
		try {
			url = new URL("http://flickr.com/services/rest/?method=flickr.auth.getFrob&api_key=d35a91cf46cbfc48c5dec2507c0c2821&api_sig=833c8e544138124000dde6aa1d52275d");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		
		SAXParserFactory spf = SAXParserFactory.newInstance();
		SAXParser sp = null;
		try {
			sp = spf.newSAXParser();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
		XMLReader xr = null;
		try {
			xr = sp.getXMLReader();
		} catch (SAXException e) {
			e.printStackTrace();
		}
		TokenParser tp = new TokenParser();
		xr.setContentHandler(tp);
		try {
			xr.parse(new InputSource(url.openStream()));
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
		frob = tp.getFrob();
		return frob;
		
	}
	
	public String authURL()
	{
		String s = secret+"api_key"+api_key+"frob"+frob+"permsdelete";
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		}
		md.update(s.getBytes(),0,s.length());
		System.out.println("getFullToken");
//		md.h
		byte[] byteSig = md.digest();
		
		StringBuffer hexString = new StringBuffer();
		for (int i=0;i<byteSig.length;i++) {
			String hex = Integer.toHexString(0xFF & byteSig[i]);
			if (hex.length() == 1) {
			    // could use a for loop, but we're only dealing with a single byte
			    hexString.append('0');
			}
			hexString.append(hex);
		}
		frobapi_sig = hexString.toString();
		
		String toReturn = "?api_key="+api_key+"&perms=delete&frob="+frob+"&api_sig="+frobapi_sig;
		return toReturn;
	}
	
	public String getToken()
	{
		String s = secret+"api_key"+api_key+"frob"+frob+"methodflickr.auth.getToken";
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		}
		md.update(s.getBytes(),0,s.length());
//		md.h
		byte[] byteSig = md.digest();
		
		StringBuffer hexString = new StringBuffer();
		for (int i=0;i<byteSig.length;i++) {
			String hex = Integer.toHexString(0xFF & byteSig[i]);
			if (hex.length() == 1) {
			    // could use a for loop, but we're only dealing with a single byte
			    hexString.append('0');
			}
			hexString.append(hex);
		}
		tokapi_sig = hexString.toString();
		
		String toReturn = "http://flickr.com/services/rest/?method=flickr.auth.getToken&api_key="+api_key+"&frob="+frob+"&api_sig="+tokapi_sig;
		URL url = null;
		try {
			url = new URL(toReturn);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		
		SAXParserFactory spf = SAXParserFactory.newInstance();
		SAXParser sp = null;
		try {
			sp = spf.newSAXParser();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
		XMLReader xr = null;
		try {
			xr = sp.getXMLReader();
		} catch (SAXException e) {
			e.printStackTrace();
		}
		TokenParser tp = new TokenParser();
		xr.setContentHandler(tp);
		try {
			xr.parse(new InputSource(url.openStream()));
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
		return tp.getToken();
	}
	public void uploadPhoto(String photo, String title, String description, String token) throws IOException, FlickrException, SAXException
	{
       Auth auth = null;

		try {
        	
            Flickr f = new Flickr(api_key,secret, new REST());
            AuthInterface authInterface = f.getAuthInterface();
        	auth = authInterface.checkToken(token);
            System.out.println("Authentication success");
            // This token can be used until the user revokes it.
        } catch (FlickrException e) {
            System.out.println("Authentication failed");
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
        RequestContext requestContext = RequestContext.getRequestContext();
        auth.setPermission(Permission.DELETE);
        requestContext.setAuth(auth);
        
        Uploader x = new Uploader(api_key, secret);
		UploadMetaData umd= new UploadMetaData();
		if (title.length() > 0) umd.setTitle(title);
		if (description.length() > 0) umd.setDescription(description);

	
		File file = new File(photo);
		InputStream is = new FileInputStream(file);
		
		// Get the size of the file
		long length = file.length();

		    
		if (length > Integer.MAX_VALUE) {

		       // File is too large
			}
		    
		        // Create the byte array to hold the data
		byte[] bytes = new byte[(int)length];

		    
		        // Read in the bytes
	    int offset = 0;
		int numRead = 0;
	    while (offset < bytes.length
		     && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
		     offset += numRead;
		}
		    
	    // Ensure all the bytes have been read in
		if (offset < bytes.length) {
			throw new IOException("Could not completely read file "+file.getName());
		}
		    
		// Close the input stream and return bytes
		  is.close();
		  x.upload(bytes, umd);
		    }
		
	}
